package mars;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

public class ZipWidgetHelper implements IObjectActionDelegate {

	private IWorkbenchPart part;
	private ISelection selection;

	public void run(IAction action) {
		if (!(selection instanceof IStructuredSelection))
			return;
		IStructuredSelection structured = (IStructuredSelection) selection;
		IProject project = (IProject) structured.getFirstElement();
		IFolder srcFolder = project.getFolder("src");
		IFolder binFolder = project.getFolder("bin");

		String srcFilePath = srcFolder.getRawLocation().toFile().toString();
		String binFilePath = binFolder.getRawLocation().toFile().toString();
		
		MessageDialog.openInformation(this.part.getSite().getShell(),
				"Readme Example", srcFilePath);

		try {
			this.zip(binFilePath + System.getProperty("file.separator")+ project.getName() + ".wgz", srcFilePath);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		// TODO Auto-generated method stub
		this.part = targetPart;

	}

	public void selectionChanged(IAction action, ISelection selection) {
		// TODO Auto-generated method stub

		this.selection = selection;
	}

	public void zip(String zipFileName, String inputFile) throws Exception {

		System.out.println("zip start...." + inputFile);
		zip(zipFileName, new File(inputFile));

	}

	public void zip(String zipFileName, File inputFile) throws Exception {
		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
				zipFileName));
		zip(out, inputFile, "");
		System.out.println("zip done");
		out.close();
	}

	public void zip(ZipOutputStream out, File f, String base) throws Exception {

		System.out.println("Zipping  " + f.getName());
		if (f.isDirectory()) {
			File[] fl = f.listFiles();
			out.putNextEntry(new ZipEntry(base + "/"));
			base = base.length() == 0 ? "" : base + "/";
			for (int i = 0; i < fl.length; i++) {
				zip(out, fl[i], base + fl[i].getName());
			}
		} else {
			out.putNextEntry(new ZipEntry(base));
			FileInputStream in = new FileInputStream(f);
			int b;
			while ((b = in.read()) != -1)
				out.write(b);
			in.close();
		}
	}

}
